package com.demo.service;

import com.demo.model.Product;
import org.springframework.stereotype.Service;
import java.util.*;

@Service
public class ProductService {
    private final Map<Long, Product> productRepo = new HashMap<>();
    private long idCounter = 1;

    public List<Product> getAllProducts() {
        return new ArrayList<>(productRepo.values());
    }
    public Product getProductById(Long id) {
        return productRepo.get(id);
    }
    public void addProduct(Product product) {
        product.setId(idCounter++);
        productRepo.put(product.getId(), product);
    }
    public void updateProduct(Product product) {
        productRepo.put(product.getId(), product);
    }
    public void deleteProduct(Long id) {
        productRepo.remove(id);
    }
    // 批量添加
    public void addProducts(List<Product> products) {
        for (Product product : products) {
            addProduct(product);
        }
    }
    // 分页查询
    public List<Product> getProductsByPage(int pageNum, int pageSize) {
        List<Product> all = getAllProducts();
        int fromIndex = Math.max(0, (pageNum - 1) * pageSize);
        int toIndex = Math.min(all.size(), fromIndex + pageSize);
        if (fromIndex > toIndex) return Collections.emptyList();
        return all.subList(fromIndex, toIndex);
    }
} 